package com.lkl.demo.provider.config;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class MyReturnListener implements RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        rabbitTemplate.setReturnsCallback(this);
    }

    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        //只要此方法执行说明交换机分发消息到队列失败
        System.out.println("消息从交换机分发到队列失败");
        //获取交换机
        String exchange = returnedMessage.getExchange();
        //获取路由key
        String routingKey = returnedMessage.getRoutingKey();
        //获取发送消息
        String msg = returnedMessage.getMessage().toString();
        //失败就再次发送
        rabbitTemplate.convertAndSend(exchange,routingKey,msg);
    }
}
